import {
	useStore
} from "../store"

let needLoadingRequestCount = 0

const startLoading = () => {
	uni.showLoading({
		title: '加载中',
	})
}

const endLoading = () => {
	uni.hideLoading()
}

const showLoading = () => {
	if (needLoadingRequestCount === 0) {
		startLoading()
	}
	needLoadingRequestCount++
}

const hideLoading = () => {
	needLoadingRequestCount--
	if (needLoadingRequestCount <= 1) {
		endLoading()
	}
}
const baseUrl = 'https://jhtest.hrtpayment.com/index.php/SmallProgramApi'

const filterParams = param => {
	let needSign = param.needSign === false ? false : true;

	const store = useStore()

	let data = param.data || {};
	let userInfo = store.userInfo;
	let share_uid = userInfo.share_uid
	data.merchant_id = userInfo.merchant_id; //商户id

	data.version = 2;

	if (userInfo.uid && needSign) {
		data.uid = userInfo.uid; //用户id
	}
	if (!data.vid && userInfo && userInfo.vid) {
		data.vid = userInfo.vid;
	}
	if (param.url != '/Store/getStore_v1' && !data.store_id && store.store_id && (parseInt(store.store_id) > 0)) {
		data.store_id = store.store_id; //门店id
	}

	if (userInfo.openid) {
		data.openid = userInfo.openid; //用户openid
	}
	if (!data.appId) {
		data.appId = userInfo.appid;
	}

	// #ifdef MP-WEIXIN
	data.original_type = 1
	// #endif
	// #ifdef MP-ALIPAY
	data.original_type = 2
	data.isIsv = userInfo.appid == userInfo.tempAppId ? true : false;
	// #endif

	if (userInfo.systemInfo && userInfo.systemInfo.model) {
		data.equip = userInfo.systemInfo.model;
	}
	console.log('data======', data, param);
	let key = uni.getStorageSync('signKey');

	if (key && needSign) {
		let keysSorted = Object.keys(data).sort(); //排序健名

		let signArr = {};

		for (let i = 0; i < keysSorted.length; i++) {
			signArr[keysSorted[i]] = data[keysSorted[i]];
		}

		data = signArr;
	}

	let signData = {
		...data
	};
	console.log(signData, 'signData======');
	let strData = modifyPostParam(data);

	let outSignFields = ['remark', 'apply_reason', 'evaluate_json'];
	if (key && needSign) {
		//剔除不需要参与签名的字段
		for (let i in outSignFields) {
			if (signData[outSignFields[i]]) {
				delete signData[outSignFields[i]];
			}
		}

		let str = modifyPostParam(signData);
		str += '&key=' + key;

		App.logDebug && console.log('sign str', str)

		str = decodeURIComponent(str);

		let sign = md5.md5(str);

		strData += '&sign=' + sign;
		data.sign = sign;
	}
	if (!param.request_type || param.request_type == 'string') {
		return strData;
	} else {
		return data
	}
}
// 修改post参数
const modifyPostParam = (obj) => {
	let query = '',
		name,
		value,
		fullSubName,
		subName,
		subValue,
		innerObj,
		i;

	for (name in obj) {
		value = obj[name];

		if (value instanceof Array) {
			for (i = 0; i < value.length; ++i) {
				subValue = value[i];
				fullSubName = name + '[' + i + ']';
				innerObj = {};
				innerObj[fullSubName] = subValue;
				query += modifyPostParam(innerObj) + '&';
			}
		} else if (value instanceof Object) {
			for (subName in value) {
				subValue = value[subName];
				fullSubName = name + '[' + subName + ']';
				innerObj = {};
				innerObj[fullSubName] = subValue;
				query += modifyPostParam(innerObj) + '&';
			}
		} else if (value !== undefined && value !== null && value !== '') query += encodeURIComponent(
				name) + '=' +
			encodeURIComponent(value) + '&';
	}

	return query.length ? query.substr(0, query.length - 1) : query;
}
export const request = (url, params = {}, isLoading = false, method = 'POST') => {
	!isLoading && showLoading()
	let postData = filterParams({
		data: params,
		needSign: params.needSign === false ? false : true
	});
	return new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + url,
			method,
			data: postData,
			header: {
				"content-type": "application/x-www-form-urlencoded"
			},
			success: res => {
				if (res.statusCode === 200) {
					if (res.data && res.data.status == -1) {
						login()
					} else {
						res.data.message = res.data.message ? res.data.message : res.data.msg;
						resolve(res.data);
					}
				} else {
					reject(msg)
					uni.showToast({
						title: '接口数据异常，稍后再试',
						icon: 'none'
					})
				}
			},
			fail: msg => {
				reject(msg)
				uni.showToast({
					title: '接口数据异常，稍后再试',
					icon: 'none'
				})
			},
			complete: e => {
				!isLoading && hideLoading()
			}
		})
	})
}


function login() {
	uni.showModal({
		title: '登陆提示',
		content: '您还未登录，暂不能体验该功能，请先登录！',
		showCancel: true,
		cancelText: '暂不登录',
		cancelColor: '#999',
		confirmText: '去登录',
		confirmColor: '#ff5c6d',
		success: function(res) {
			if (res.confirm) {
				uni.navigateTo({
					url: '/pages/my/my'
				});
			}
		}
	});
}


